package com.solute.web.commons.header.service;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.solute.domain.SolutionVO;
import com.solute.domain.TagVO;
import com.solute.utils.services.ImageService;
import com.solute.utils.services.SolutionService;
import com.solute.utils.services.TagService;

@Service
public class HeaderService {

	private static final Logger logger = LoggerFactory
			.getLogger(HeaderService.class);
	
	private @Autowired ImageService imageService;
	private @Autowired TagService tagService;
	private @Autowired SolutionService solutionService;

	@Transactional
	public void addSolution(MultipartFile[] problemImages,
			MultipartFile[] solutionImages, String[] tags, SolutionVO solutionVO) {
		solutionVO.setId(UUID.randomUUID().toString());
		solutionVO.setSolutionImageGid(createImageGroup(solutionImages));
		solutionVO.setProblemImageGid(createImageGroup(problemImages));
		solutionVO.setTagGid(createTagGroup(tags));
		
		solutionService.add(solutionVO);
	}
	
	@Transactional
	private String createImageGroup(MultipartFile []images) {
		if(images != null) {
			String []ids = new String[images.length];
			for(int i = 0 ; i < images.length ; ++i) {
				ids[i] = UUID.randomUUID().toString();
				imageService.add(ids[i], images[i]);	
			}
			return imageService.createImageGroup(ids);
		} else {
			return null;
		}
	}
	
	@Transactional
	private String createTagGroup(String []tags) {
		String []ids = new String[tags.length];
		for(int i = 0 ; i < tags.length ; ++i) {
			TagVO tagVO = tagService.getByTag(tags[i]);
			if(tagVO == null) {
				ids[i] = UUID.randomUUID().toString();
				tagService.add(ids[i], tags[i]);
			} else {
				ids[i] = tagVO.getId();
			}
		}
		return tagService.createTagGroup(ids);
	}
}
